package com.yanqu.road.server.cross3server.cmd.activity.entername;

import com.yanqu.road.entity.activity.entername.ActivityGroupMatch;
import com.yanqu.road.entity.activity.entername.UserEnterName;
import com.yanqu.road.logic.activity.entername.ChannelEnterNameHelper;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.pb.cross3.activity.EnterNameProto;
import com.yanqu.road.server.command.Cmd;
import com.yanqu.road.server.command.Command;
import com.yanqu.road.server.connect.CrossAgentLinkedControl;
import com.yanqu.road.server.cross3server.manager.Cross3EnterNameMgr;
import com.yanqu.road.server.logic.MessageHelper;
import com.yanqu.road.server.protocol.Cross3Protocol;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.utils.YanQuMessageUtils;
import io.netty.channel.ChannelHandlerContext;

import java.util.List;
import java.util.Map;

@Cmd(code = Cross3Protocol.C3_ENTER_NAME_ALL_NAME_SYNC_TO_SEVER, desc = "同步整个渠道报名数据(全量)（来自区服）")
public class Cross3EnterNameAllSyncFromCrossCmd implements Command {

    @Override
    public void execute(ChannelHandlerContext ctx, YanQuMessage yanQuMessage) throws Exception {

        EnterNameProto.Cross3EnterNameAllSyncReqMsg reqMsg = EnterNameProto.Cross3EnterNameAllSyncReqMsg.parseFrom(yanQuMessage.getBytes());
        long serverId = CrossAgentLinkedControl.getLinkedClient(ctx).getServerId();
        int activityId = reqMsg.getActivityId();
        Map<Long, UserEnterName> nameMap = Cross3EnterNameMgr.getNameMap().get(activityId);
        List<ActivityGroupMatch> matchList = Cross3EnterNameMgr.getMatchMap().get(activityId);
        if(nameMap != null) {
            EnterNameProto.ChannelEnterNameAllSyncMsg.Builder sync = EnterNameProto.ChannelEnterNameAllSyncMsg.newBuilder();
            sync.setActivityId(activityId);
            sync.setServerId(serverId);
            for (Map.Entry<Long, UserEnterName> entry : nameMap.entrySet()) {
                UserEnterName enterName = entry.getValue();
                if(enterName.getServerId() == serverId){
                    sync.addName(ChannelEnterNameHelper.buildUserEnterNameMsg(enterName));
                }
            }
            if(matchList != null){
                for (int i = 0; i < matchList.size(); i++) {
                    ActivityGroupMatch match = matchList.get(i);
                    EnterNameProto.ChannelEnterNameGroupingMsg.Builder builder = EnterNameProto.ChannelEnterNameGroupingMsg.newBuilder();
                    builder.setGroupId(match.getGroupId());
                    builder.addAllZoneList(match.getZoneIdList());
                    builder.setEnemyGroupId(match.getEnemyGroupId());
                    sync.addGroup(builder);
                }
            }
            MessageHelper.sendPacket(serverId, 0, YanQuMessageUtils.buildMessage(Protocol.S_ENTER_NAME_ALL_NAME_SYNC_FROM_CROSS, sync));
        }
    }
}
